package zsc.ruanc.practicaltraining.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import io.swagger.annotations.Api;
import zsc.ruanc.practicaltraining.exception.ApiException;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class TokenUtils {


    /**
     *
     * @param id 用户id
     * @param Role 用户身份
     * @param key
     * @return
     */
     public static String create(int id, String Role, String name, String key) {

         Date iatDate = new Date();
         // expire time
         Calendar nowTime = Calendar.getInstance();
         //1小时有效期
         nowTime.add(Calendar.HOUR, 1);
         Date expiresDate = nowTime.getTime();


         String token = JWT.create().withClaim("id", id)
                 .withClaim("role", Role)
                 .withSubject(name)
                 .withExpiresAt(expiresDate) // 过期时间
                 .sign(Algorithm.HMAC256(key));
         return token;

     }

    /**
     * 解密
     * @param token
     * @param key
     * @return
     */
     public static DecodedJWT deToken(String token, String key) {
         JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(key)).build();
         try {
             DecodedJWT decodeJWT = jwtVerifier.verify(token);
             return decodeJWT;
         } catch (JWTDecodeException e) {
             throw new ApiException(-9, e.getMessage());
         } catch (IllegalArgumentException e) {
             throw new ApiException(-9, "无效的格式");
         }  catch (SignatureVerificationException e) {
             throw new ApiException(-9, "无效的令牌");
         }
     }

    /**
     * 获取id值，做为redis的key取出value(密匙)
     * @param token
     * @return
     */
     public static int getRedisKey(String token) {

         try {
             Claim c = JWT.decode(token).getClaim("id");
             int id = c.asInt();
             return id;
         } catch (JWTDecodeException e) {
             throw new ApiException(-9, "token被篡改");
         } catch (IllegalArgumentException e) {
             throw new ApiException(-9, "无效的格式");
         }
     }

     public static String refresh(String token, String key) {
         DecodedJWT decodedJWT = deToken(token, key);
         return create(decodedJWT.getClaim("id").asInt(), decodedJWT.getClaim("role").asString(), decodedJWT.getSubject(), key);
     }

    /**
     * 生成随机秘钥
     * @return
     */
    public static String randomKey() {
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*()_+=-|/?[],.;";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < 10; i++) {
            int number = random.nextInt(85);
            sb.append(str.charAt(number));
        }
        return sb.toString();
     }





}
